import { Page } from 'puppeteer';
import { IUserBasic } from './_base';

export interface IVideoMeta {
    bvid: string;
    videoTitle: string;
    videoCoverSrc: string;
    uploadDate: string;
    viewCount: string;
    up: IUserBasic;
}

export function spacelinkToUid(spaceLink: string): string {
    // https://space.bilibili.com/86221452?spm_id_from=333.788.0.0
    return spaceLink.split('?')[0].split('/').pop()!;
}

export function uidToSpacelink(uid: string): string {
    return `https://space.bilibili.com/${uid}`;
}

export function TemplateVideoUrl(BVid: string): string {
    return `https://www.bilibili.com/video/${BVid}`;
}

export async function fetchVideoMeta(page: Page, BVid: string): Promise<IVideoMeta> {
    const url = TemplateVideoUrl(BVid);
    await page.goto(url);
    // 等待1秒
    await new Promise(resolve => setTimeout(resolve, 5000));
    await page.waitForSelector('#wxwork-share-pic');
    const wxworkSharePic = await page.$('#wxwork-share-pic');
    const videoTitle = await page.$eval('.video-title', (el) => el.textContent);
    const wxworkSharePicSrc = await wxworkSharePic?.evaluate((el) => el.getAttribute('src'));
    const pubdateIpText = await page.$eval('.pubdate-ip-text', (el) => el.textContent);
    const viewText = await page.$eval('.view-text', (el) => el.textContent);
    const biliAvatarFace = await page.$eval('img.bili-avatar-face', (el) => el.getAttribute('data-src'));
    const upSpaceLink = await page.$eval('a.up-avatar', (el) => el.getAttribute('href'));
    const _upName = await page.$eval('.up-name', (el) => el.textContent);
    const upName = _upName?.trim();

    const meta = {
        bvid: BVid,
        videoTitle,
        videoCoverSrc: wxworkSharePicSrc,
        uploadDate: pubdateIpText,
        viewCount: viewText,
        up: {
            uid: parseInt(spacelinkToUid(upSpaceLink!)),
            nickname: upName!,
            avatar: biliAvatarFace!,
            fans: 0,
        } as IUserBasic,
    } as IVideoMeta;
    console.log(meta);

    return meta;
}